/*
 * 创建日期 2005-10-9
 *
 * 更改所生成文件模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
package com.vanda.report;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.GenericValidator;

import com.vanda.report.cfg.Configuration;
import com.vanda.report.cfg.ReportCfgBean;
import com.vanda.report.element.Element;
import com.vanda.report.element.ReportElement;
import com.vanda.report.element.SetElement;
import com.vanda.util.Globals;
import com.vanda.util.LogFunc;
/**
 * @author wkf5985
 *
 * 更改所生成类型注释的模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
public class ReportAccessor {

	private static Log log = LogFactory.getLog(Configuration.class);
	private String reportPath = null;

	static {
		init();
	}

	private static void init() {
		try {
			(new Configuration()).configure();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
		}
	}

	/**
	 * @return
	 */
	public static ReportAccessor getInstance() {
		return new ReportAccessor();
	}

	public ReportElement getReportElement(String reportID) {
		ReportElement element =
			(ReportElement) ReportCfgBean.getReport(reportID);

		return element;
	}

	public String getSelectParameters(ReportSelectData selectData) {
		String reportID = selectData.getReportNo();
		ReportElement element =
			(ReportElement) ReportCfgBean.getReport(reportID);

		try {
			if (!GenericValidator
				.isBlankOrNull(element.getSelect_parameters())) {
				return element.getSelect_parameters();
			}

			//找到Set标签
			List subList = element.getSubElements();
			for (int i = 0; i < subList.size(); i++) {
				Element subElement = (Element) subList.get(i);
				if (subElement instanceof SetElement) {
					ReportData reportData = new ReportData();
					reportData.setSelectData(selectData);
					ReportInnerData innerData = new ReportInnerData(reportData);
					subElement.execute(innerData);

					String parameters =
						(String) innerData.getHmParams().get(
							"select_parameters");
					if (!GenericValidator.isBlankOrNull(parameters)) {
						return parameters;
					}
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}

	/**
	 * 运行报表,并将生成的报表excel存入指定的目录
	 * @param reportID 报表ID
	 * @param reportData 报表数据类
	 * @param path 报表存放路径
	 * @return 返回生成报表的文件名
	 * @throws ReportException
	 */
	public String runReport(
		String reportID,
		ReportData reportData
		)
		throws ReportException {

		return runReport(reportID, reportData, null, null);
	}
	
	public String runReport(
		String reportID,
		ReportData reportData,
		String path
		)
		throws ReportException {

		return runReport(reportID, reportData, path, null);
	}

	public String runReport(
		String reportID,
		ReportData reportData,
		String path,
		String fileName)
		throws ReportException {

		if (GenericValidator.isBlankOrNull(path)) {
			path = Globals.getValue(Configuration.SYSTEM_REPORT_OUTDIR);
		}else{
			path = Globals.getValue(Configuration.SYSTEM_REPORT_OUTDIR) + "/" +path;
		}

		//如果是调试,则每次产生实例的同时重读报表配置文件
		int debug = Globals.getIntValue("debug.status");
		if(debug == 1){
			init();
		}
		//end

		ReportElement element =
			(ReportElement) ReportCfgBean.getReport(reportID);
		if (element == null) {
			throw new ReportException("Report[" + reportID + "] is not exist!");
		}
		element = (ReportElement) element.clone();

		// 执行报表
		element.execute(reportData);

		//如果报表状态为empty,则不生成文件
		String status = reportData.getStatus();
		if (status != null && status.equals(Constansts.ReportRunFlag_Empty)) {
			return null;
		}

		// 报表名称
		String name = fileName;
		FileOutputStream fos = null;
		try {
			if (GenericValidator.isBlankOrNull(name))
				name =
					getFileName(
						element.getId(),
						reportData.getSelectData());
			
			createDir(path);
			String fullPathName = path + "/" + name;

			fos = new FileOutputStream(fullPathName);
			reportData.getWorkbook().write(fos);
			reportPath = fullPathName;
		} catch (Exception e) {
			LogFunc.error(e);
			throw new ReportException(e);
		} finally {
			try {
				if(fos != null)
					fos.close();
			} catch (Exception e) {
				throw new ReportException(e);
			}
		}

		return name;
	}
	
	private void createDir(String path){
		File dir = new File(path);
		//如果不存在，则增加目录
		if(!dir.exists()){
			dir.mkdir();
		}
	}

	/**
	 * 取得文件名
	 * @param accessor
	 * @return
	 * @throws Exception
	 */
	private String getFileName(String name, Object selectData)
		throws Exception {
		/*if (selectData instanceof ReportSelectData) {
			return name
				+ "_"
				+ ((ReportSelectData) selectData).getId()
				+ ".xls";
		} else {
			DBAccessor accessor = DBFactory.getAccessor();
			Date today = CFITools.getDBToday(accessor);
			DateKeyGenerator keyGenerator =
				DateKeyGenerator.getInstance(
					accessor,
					ReportAccessor.KEY,
					today);
			long key = keyGenerator.getNextKey(accessor, today);
			DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
			NumberFormat numberFormat = new DecimalFormat("0000");
			String systemCode =
				dateFormat.format(today) + numberFormat.format(key);
			return name + "_" + systemCode + ".xls";
		}*/
		
		return name+System.currentTimeMillis()+".xls";
	}

	/**
	 * @return
	 */
	public String getReportPath() {
		return reportPath;
	}

}
